package com.zhangyu.shadow.repair.delegate.luncher;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.zhangyu.shadow.repair.R;
import com.zhangyu.shadow.repair.config.RequestUrls;
import com.zhangyu.shadow.repair.delegate.bean.BusHistoryBean;
import com.zhangyu.shadow.repair.event.ChooseSearchBusEvent;
import com.zhangyu.shadow.repair.intercept.DataIntercept;
import com.zhangyu.shadow.repair.manager.AccountManager;

import org.greenrobot.eventbus.EventBus;

import st.lib.base.net.callback.IError;
import st.lib.base.net.callback.ISuccess;
import st.lib.base.net.rx.RxRestClient;
import st.lib.base.ui.progress.sweetalert.DialogLoader;
import st.lib.base.ui.progress.sweetalert.IDialogClickListener;
import st.lib.base.ui.recycler.BaseDecoration;
import st.lib.base.ui.recycler.MultipleItemEntity;
import st.lib.base.ui.recycler.RecyclerViewNoBugLinearLayoutManager;
import st.lib.base.ui.search.SearchClearEditText;
import st.lib.base.util.utilcode.util.DimensionConvert;

/**
 * @author zhangyu
 * @date 2018/11/26
 */

public class RepairDialog extends DialogFragment {
    private DialogLoader mDialogLoader;
    private int type;

    public static RepairDialog newInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        RepairDialog dialog = new RepairDialog();
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getContext(), R.style.BottomDialog);
        dialog.setTitle(type == 0 ? "小修报修" : "保养报修");
        dialog.setCanceledOnTouchOutside(true);
        mDialogLoader = new DialogLoader(getContext());
        View view = LayoutInflater.from(getContext()).
                inflate(R.layout.dialog_bus_repair, null);
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.CENTER;
            lp.height = DimensionConvert.getHeight3(getContext())*2;
            lp.width = DimensionConvert.getWidth3(getContext())*2;
            window.setAttributes(lp);
        }

        Toolbar toolbar = view.findViewById(R.id.toolbar_search);
        final SearchClearEditText editText = view.findViewById(R.id.et_search);
        editText.setHint("请输入车辆编号");
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String code = editText.getText().toString();
                    if (!code.isEmpty()) {
                        search(code, type);
                    }
                    return true;
                }
                return false;
            }
        });
        toolbar.inflateMenu(R.menu.search);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int i = item.getItemId();
                if (i == R.id.menu_search) {
                    String code = editText.getText().toString();
                    if (!code.isEmpty()) {
                        search(code, type);
                    }
                }
                return true;
            }
        });
        final RecyclerView recyclerView = view.findViewById(R.id.recycler_view_history);
        recyclerView.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(BaseDecoration.create(ContextCompat.getColor(getContext(),
                R.color.app_background), 1));
        final HistoryBusAdapter adapter = new HistoryBusAdapter(R.layout.item_repair_bus_history,
                AccountManager.getInstance().getRepairBus());
        adapter.setEmptyView(R.layout.view_recycler_no_data, (ViewGroup) recyclerView.getParent());
        recyclerView.setAdapter(adapter);
        recyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BusHistoryBean busHistoryBean = (BusHistoryBean) adapter.getItem(position);
                if (busHistoryBean != null) {
                    search(busHistoryBean.getVehicleCode(), busHistoryBean.getType());
                }
            }

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                adapter.remove(position);
                AccountManager.getInstance().removeBus((BusHistoryBean) adapter.getItem(position));
            }
        });
        view.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!adapter.getData().isEmpty()) {
                    mDialogLoader.showWarning("清空历史记录", "请确认", new IDialogClickListener() {
                        @Override
                        public void onClick() {
                            AccountManager.getInstance().clearRepairHistory();
                            adapter.setNewData(null);
                            mDialogLoader.clearDialog();
                        }
                    });
                }
            }
        });
        return dialog;
    }

    private void search(String code, final int type) {
        mDialogLoader.showProgressDialog(true, "正在搜索", "请稍候...");
        RxRestClient.builder()
                .url(type == 0 ?
                        RequestUrls.URL_SEARCH_BUS_FIX :
                        RequestUrls.URL_MAINTAIN_SEARCH_VEHICLE)
                .params("vehicleCode", code)
                .params(AccountManager.getInstance().getBaseInfo())
                .interceptor(new DataIntercept())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (response != null) {
                            convertData(type, response);
                        } else {
                            mDialogLoader.stopProgressWithFailed(type == 1 ?
                                            "无此车辆的保养计划" : "无此车辆",
                                    "请确认");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.stopProgressWithFailed(msg, "请确认");
                    }
                })
                .build()
                .post();
    }

    private void convertData(int type, String response) {
        MultipleItemEntity entity;
        if (type == 0) {
            entity = BusDataConverter.convertToRepair(response);
        } else {
            entity = BusDataConverter.convertToMaintain(response);
        }
        if (entity != null) {
            mDialogLoader.clearDialog();
            EventBus.getDefault().post(new ChooseSearchBusEvent(entity));
            dismiss();
        } else {
            mDialogLoader.stopProgressWithFailed("数据解析错误", null);
        }
    }

}
